package JavaSE;
import java.util.Scanner;
//求斐波那契数列的第n项。(迭代实现)
public class time_2025_07_04求斐波那契数列的第n项 {
    public static int fibonacci(int n){
        if(n<0){
            return -1;
        }
        if(n==0){
            return 0;
        }
        if(n==1){
            return 1;
        }
        else {
            int first = 0;
            int second = 1;
            int result = 0;

            for (int i = 2; i <= n; i++) {
                result = first + second;
                first = second;
                second = result;
            }
            return result;
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入斐波那契数列的项数n（n>=0）：");
        int n = scanner.nextInt();
        int result = fibonacci(n);
        if(result==-1){
            System.out.println("输入错误！n不能为负数！");
        }else{
            System.out.println("斐波那契数的第"+n+"项是"+result);
        }
        scanner.close();
    }
}
